package com.general.framework.cc.limit;

import com.google.common.util.concurrent.RateLimiter;

import java.util.HashMap;
import java.util.Map;

public class LimitHelper {
    private LimitHelper() {
    }

    ;
    /**
     * 设置每个限流类型到底限制每秒多少次请求
     */
    private static Map<String, Integer> mapLimitCount = new HashMap<>();

    static {
        mapLimitCount.put(LimitHelper.LIMIT_TYPE_NORMAL_SAVE_ORDER, 5);
    }

    public static final String LIMIT_TYPE_NORMAL_SAVE_ORDER = "normal_save_order";
    /**
     * 缓存每个限流类型对应的限流器对象
     */
    private static final Map<String, RateLimiter> mapRateLimiter = new HashMap<>();

    /**
     * 根据限流类型获取对应的限流器对象
     */
    public static synchronized RateLimiter getRateLimiter(String type) {
        RateLimiter rateLimiter = mapRateLimiter.get(type);
        if (rateLimiter == null) {
            rateLimiter = RateLimiter.create(mapLimitCount.get(type));
            mapRateLimiter.put(type, rateLimiter);
        }
        return rateLimiter;
    }
}
